<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/16
 * Time: 13:51
 */

namespace app\bm\controller;

use think\Db;
use think\Request;
use app\common\model\Goods AS GoodsModel;

class Goods extends Common
{

    public function index()
    {
        // 查询状态为1的用户数据 并且每页显示10条数据
        $list = Db::name('Goods')->order("id DESC")->paginate(10);
        // 把分页数据赋值给模板变量list
        $this->assign('list', $list);
        // 渲染模板输出
        return $this->view->fetch();
    }

    public function create()
    {
        $Item = new \app\common\model\Item();
        $category_list = $Item->lists();

        $this->assign([
            'category_list'=>$category_list
        ]);
        return $this->view->fetch();
    }

    public function save(Request $request)
    {
        if($request->isPost()){
            $Post = new \app\common\model\Goods();
            $Post->content = $request->post('content','','stripslashes');
            $res = $Post->together(['postcontent'=>['content']])->save($request->post());
            if($res){
                return $this->success("添加成功");
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function edit(Request $request)
    {
        $id = $request->param('id');
        if($id){
            $Post = new \app\common\model\Goods();
            $info = $Post->info($id);
            if($info){
                // 获取分类
                $Category = new \app\common\model\Item();
                $category_list = $Category->lists();
                $this->assign([
                    'category_list'=>$category_list,
                    'info'=>$info
                ]);
                return $this->view->fetch();
            }else{
                return $this->error('数据错误');
            }
        }else{
            return $this->error('参数错误');
        }
    }

    public function update(Request $request)
    {
        if($request->isPost()){
            $id = $request->post('id');
            $Post = GoodsModel::get($id);
            $Post->goodscontent->content= $request->post('content','','stripslashes');
            $res = $Post->together('goodscontent')->save($request->post());
            if($res){
                return $this->success("修改成功");
            }
        }else{
            return $this->error('非法请求');
        }
    }

    // 删除
    public function delete(Request $request)
    {
        $id = $request->param('id');

        if ( empty($id) ) {
            return $this->error('请选择要操作的数据!');
        }

        $map = array('id' => array('in', $id) );
        if(Db::name('Goods')->where($map)->delete()){
            //记录行为 todo...
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败！');
        }
    }
}